<template>
    <div class="page_root" data-page-name="创建配送方案" data-page-identification="t_ziomekx4ys">
      <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
        <!-- begin vid_rkqe6n181v 自定义模板_wj7t65m9yw -->
        <a-spin :spinning="loading">
          <div class="create-plan">
            <a-steps :current="current" class="step">
              <a-step title="需求导入" />
              <a-step title="企业发货上限" />
              <a-step title="企业至区域发货约束" />
              <a-step title="方案优化" />
            </a-steps>
            <div class="content">
              <div v-show="current === 0" class="import-div">
                <a-row :gutter="16" class="top-row">
                  <a-col :span="6"
                    ><div class="top-div">
                      <div>全部区域总需求量：</div>
                      <div style="display: flex">
                        <a-tooltip>
                          <template #title>{{ statistics.num1 }}</template>
                          <span class="top-num">{{ statistics.num1 }}</span>
                        </a-tooltip>
                        <span style="color: #e02020">吨</span>
                      </div>
                    </div></a-col
                  >
                  <a-col :span="6"
                    ><div class="top-div">
                      <div>全部区域袋装需求量：</div>
                      <div style="display: flex">
                        <a-tooltip>
                          <template #title>{{ statistics.num2 }}</template>
                          <span class="top-num">{{ statistics.num2 }}</span>
                        </a-tooltip>
                        <span style="color: #e02020">吨</span></div
                      >
                    </div></a-col
                  >
                  <a-col :span="6"
                    ><div class="top-div">
                      <div>全部区域散装需求量：</div>
                      <div style="display: flex">
                        <a-tooltip>
                          <template #title>{{ statistics.num3 }}</template>
                          <span class="top-num">{{ statistics.num3 }}</span>
                        </a-tooltip>
                        <span style="color: #e02020">吨</span></div
                      >
                    </div></a-col
                  >
                  <a-col :span="6"
                    ><div class="top-div">
                      <div>全部区域熟料需求量：</div>
                      <div style="display: flex">
                        <a-tooltip>
                          <template #title>{{ statistics.num4 }}</template>
                          <span class="top-num">{{ statistics.num4 }}</span>
                        </a-tooltip>
                        <span style="color: #e02020">吨</span></div
                      >
                    </div></a-col
                  >
                </a-row>
                <div class="top-title">
                  <a-row class="first-top-row" :gutter="24">
                    <a-col :span="3">区域需求量列表</a-col>
                    <a-col :span="4" class="first-top-row-check">
                      <a-checkbox v-model:checked="distributionRemain" class="distribution-remain">剩余发货量配送至运费最低区域</a-checkbox>
                    </a-col>
                    <a-col :span="5" style="font-weight: normal; padding: 0 12px 0 24px">
                      <a-form-item label="区域名称">
                        <a-input v-model:value="filter1.name" placeholder="请输入区域名称" />
                      </a-form-item>
                    </a-col>
                    <a-col :span="5" class="normal-col">
                      <a-form-item label="包装类型">
                        <a-select placeholder="请选择包装类型" v-model:value="filter1.packageType" :options="packageTypeList" allowClear @mouseenter="getUpperPackageList" />
                      </a-form-item>
                    </a-col>
                    <a-col :span="4">
                      <a-space>
                        <a-button class="btn-color" @click="handlerFilterTable1">查询</a-button>
                        <a-button @click="hanlderResetTable1" class="border-btn">重置</a-button>
                      </a-space>
                    </a-col>
                    <a-col :span="3" style="display: flex; justify-content: end; position: relative; top: -12px">
                      <a-space>
                        <a-button @click="handlerDownloadTemplate" class="border-btn">下载模板</a-button>
                        <a-upload :file-list="[]" :before-upload="beforeUpload">
                          <a-button class="border-btn">导入Excel</a-button>
                        </a-upload>
                      </a-space></a-col
                    >
                  </a-row>
                </div>
                <a-table
                  :columns="columns1"
                  v-model:current="currentPage"
                  :data-source="tableData1"
                  @change="pageChange"
                  bordered
                  :row-class-name="
                                      (_record, index) => (index % 2 === 1 ? 'table-striped-even' : 'table-striped-odd')
                                  "
                >
                  <template #bodyCell="{ column, index }">
                    <template
                      v-if="
                                              column.dataIndex === 'demand' && tableData1[(currentPage - 1) * 10 + index]
                                          "
                    >
                      <a-input-number style="width: 50%" v-model:value="tableData1[(currentPage - 1) * 10 + index].demand" :min="0" @change="debounceGetStatistics" />
                    </template>
                  </template>
                </a-table>
              </div>
              <div v-show="current === 1">
                <div class="second-top">
                  <a-col :span="6" style="margin-top: -8px">
                    <a-form ref="secondFormRef" :model="secondFormData">
                      <a-form-item
                        label="选择企业发货上限"
                        class="date-group"
                        name="upperLimit"
                        :rules="[
                                                  {
                                                      required: true,
                                                      message: '请选择企业发货上限',
                                                      trigger: 'change'
                                                  }
                                              ]"
                      >
                        <a-select
                          placeholder="请选择企业发货上限"
                          style="width: 100%"
                          v-model:value="secondFormData.upperLimit"
                          :options="upperLimitList"
                          @select="handlerUpperChange"
                          @mouseenter="getUpperVsesion"
                        />
                      </a-form-item>
                    </a-form>
                  </a-col>
                </div>
                <div class="second-table">
                  <div class="top-title">
                    <a-row :gutter="24" class="second-top-row">
                      <a-col :span="2">企业发货上限</a-col>
                      <a-col :span="5" offset="9" class="normal-col">
                        <a-form-item label="企业名称" name="enterpriseName">
                          <a-input v-model:value="filter2.enterpriseName" placeholder="请输入企业名称" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="5" class="normal-col">
                        <a-form-item label="包装类型">
                          <a-select placeholder="请选择包装类型" v-model:value="filter2.packageType" :options="packageTypeList" allowClear @mouseenter="getUpperPackageList" /> </a-form-item
                      ></a-col>
                      <a-col :span="3" style="display: flex; justify-content: end; top: -12px">
                        <a-space>
                          <a-button class="btn-color" @click="handlerSearchUpper">查询</a-button>
                          <a-button @click="handlerResetUpper" class="border-btn">重置</a-button>
                        </a-space>
                      </a-col>
                    </a-row>
                  </div>
                  <a-table
                    :columns="columns2"
                    :dataSource="dataSource2"
                    size="small"
                    bordered
                    :row-class-name="
                                          (_record, index) =>
                                              index % 2 === 1 ? 'table-striped-even' : 'table-striped-odd'
                                      "
                  />
                </div>
              </div>
              <div v-show="current === 2">
                <a-form :model="thirdFormData" ref="thirdFormRef">
                  <div style="border-bottom: 1px solid #d9d9d9">
                    <a-row :gutter="24" class="third-top-row" style="margin-top: -8px">
                      <a-col :span="7">
                        <a-form-item
                          label="选择企业至区域发货约束"
                          name="regionConstrainVersion"
                          :rules="[
                                                      {
                                                          required: true,
                                                          message: '请选择企业至区域发货约束',
                                                          trigger: 'blur'
                                                      }
                                                  ]"
                        >
                          <a-select
                            placeholder="请选择企业至区域发货约束"
                            v-model:value="thirdFormData.regionConstrainVersion"
                            :options="regionConstraintList"
                            @select="handlerConstraintChange"
                            @mouseenter="getConstraintListVersion"
                          />
                        </a-form-item>
                      </a-col>
  
                      <a-col :span="6">
                        <a-form-item
                          label="选择运费版本"
                          name="freightVersion"
                          :rules="[
                                                      { required: true, message: '请选择运费版本', trigger: 'blur' }
                                                  ]"
                        >
                          <a-select
                            placeholder="请选择运费版本"
                            v-model:value="thirdFormData.freightVersion"
                            :options="freightVersionList"
                            @mouseenter="getfreightVersion"
                            @select="handlerFreightSelect"
                          />
                        </a-form-item>
                      </a-col>
                      <a-col :span="6">
                        <a-form-item
                          label="选择出厂价版本"
                          name="factoryPriceVersion"
                          :rules="[
                                                      { required: true, message: '请选择出厂价版本', trigger: 'blur' }
                                                  ]"
                        >
                          <a-select
                            v-model:value="thirdFormData.factoryPriceVersion"
                            placeholder="请选择出厂价版本"
                            :options="customerConstraintList"
                            @mouseenter="getcustomFactoryPriceVersion"
                            @select="handlerFactoryPriceSelect"
                          />
                        </a-form-item>
                      </a-col>
                    </a-row>
                  </div>
                </a-form>
                <div class="third-table">
                  <div class="top-title">
                    <a-row :gutter="24" class="third-top-row">
                      <a-col :span="3">企业至区域发货约束</a-col>
                      <a-col :span="5" offset="3" class="normal-col">
                        <a-form-item label="企业名称">
                          <a-input v-model:value="filter3.enterpriseName" placeholder="请输入企业名称" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="5" class="normal-col">
                        <a-form-item label="区域名称">
                          <a-input v-model:value="filter3.areaName" placeholder="请输入区域名称" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="5" class="normal-col">
                        <a-form-item label="包装类型">
                          <a-select placeholder="请选择包装类型" v-model:value="filter3.packingTypeName" :options="packageTypeList" allowClear @mouseenter="getUpperPackageList" /> </a-form-item
                      ></a-col>
                      <a-col :span="3" style="display: flex; justify-content: end; top: -12px">
                        <a-space>
                          <a-button class="btn-color" @click="handlerConstraintSearch">查询</a-button>
                          <a-button @click="handlerConstraintReset" class="border-btn">重置</a-button>
                        </a-space>
                      </a-col>
                    </a-row>
                  </div>
                  <a-table
                    :columns="columns3"
                    :dataSource="dataSource3"
                    size="small"
                    bordered
                    :row-class-name="
                                          (_record, index) =>
                                              index % 2 === 1 ? 'table-striped-even' : 'table-striped-odd'
                                      "
                  />
                </div>
              </div>
              <div v-show="current === 3">
                <div class="success" v-if="saveSuccess">
                  <a-result status="success">
                    <template #title>
                      <span style="color: #52c41a; font-size: 20px">方案保存成功!</span>
                    </template>
                    <template #subTitle>
                      <span style="color: black; font-size: 16px">您已保存方案“{{ saveFormData.name }}”,点击【关闭】按钮退出。</span>
                    </template>
                  </a-result>
                </div>
                <div v-else>
                  <div class="four-top">
                    <div class="four-title">
                      <div class="four-title-item-first">
                        <div class="first-item-title"> 运输总费用 </div>
                        <div class="first-item-bottom">
                          <a-tooltip>
                            <template #title>{{ statistics2.num1 }}</template>
                            <span class="bottom-num">{{ statistics2.num1 }}</span>
                          </a-tooltip>
  
                          <div class="statis-suffix">元</div>
                        </div>
                      </div>
                      <div class="four-title-item">
                        <div class="item-title">汽运费用</div>
                        <div class="item-bottom">
                          <a-tooltip>
                            <template #title>{{ statistics2.num2 }}</template>
                            <span class="bottom-num">{{ statistics2.num2 }}</span>
                          </a-tooltip>
                          <span class="statis-suffix">元</span></div
                        >
                      </div>
                      <div class="four-title-item"
                        ><div class="item-title">火运费用</div>
                        <div class="item-bottom">
                          <a-tooltip>
                            <template #title>{{ statistics2.num3 }}</template>
                            <span class="bottom-num">{{ statistics2.num3 }}</span>
                          </a-tooltip>
                          <span class="statis-suffix">元</span>
                        </div>
                      </div>
                      <div class="four-title-item"
                        ><div class="item-title">船运费用</div>
                        <div class="item-bottom"
                          ><a-tooltip>
                            <template #title>{{ statistics2.num4 }}</template>
                            <span class="bottom-num">{{ statistics2.num4 }}</span> </a-tooltip
                          ><span class="statis-suffix">元</span></div
                        ></div
                      >
                      <div class="four-title-item"
                        ><div class="item-title">散装总配送量</div>
                        <div class="item-bottom"
                          ><a-tooltip>
                            <template #title>{{ statistics2.num5 }}</template>
                            <span class="bottom-num">{{ statistics2.num5 }}</span> </a-tooltip
                          ><span class="statis-suffix">吨</span></div
                        ></div
                      >
                      <div class="four-title-item"
                        ><div class="item-title">袋装总配送量</div>
                        <div class="item-bottom"
                          ><a-tooltip>
                            <template #title>{{ statistics2.num26 }}</template>
                            <span class="bottom-num">{{ statistics2.num6 }}</span> </a-tooltip
                          ><span class="statis-suffix">吨</span></div
                        ></div
                      >
                      <div class="four-title-item"
                        ><div class="item-title">熟料总配送量</div>
                        <div class="item-bottom"
                          ><a-tooltip>
                            <template #title>{{ statistics2.num7 }}</template>
                            <span class="bottom-num">{{ statistics2.num7 }}</span> </a-tooltip
                          ><span class="statis-suffix">吨</span></div
                        ></div
                      >
                    </div>
                  </div>
                  <div class="top-title">
                    <a-row :gutter="24" class="third-top-row">
                      <a-col :span="3">方案优化</a-col>
                      <a-col :span="5" offset="3" class="normal-col">
                        <a-form-item label="企业名称">
                          <a-input v-model:value="filter4.enterpriseName" placeholder="请输入企业名称" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="5" class="normal-col">
                        <a-form-item label="区域名称">
                          <a-input v-model:value="filter4.areaName" placeholder="请输入区域名称" />
                        </a-form-item>
                      </a-col>
                      <a-col :span="5" class="normal-col">
                        <a-form-item label="包装类型">
                          <a-select placeholder="请选择包装类型" v-model:value="filter4.packingTypeName" :options="packageTypeList" allowClear @mouseenter="getUpperPackageList" /> </a-form-item
                      ></a-col>
                      <a-col :span="3" style="display: flex; justify-content: end; top: -12px">
                        <a-space>
                          <a-button class="btn-color" @click="handlerFilterTable4">查询</a-button>
                          <a-button @click="hanlderResetTable4" class="border-btn">重置</a-button>
                        </a-space>
                      </a-col>
                    </a-row>
                  </div>
                  <a-table
                    :columns="columns4"
                    :data-source="tableData4"
                    size="small"
                    bordered
                    :row-class-name="
                                          (_record, index) =>
                                              index % 2 === 1 ? 'table-striped-even' : 'table-striped-odd'
                                      "
                  >
                    <template #bodyCell="{ column, index, record, text }">
                      <template v-if="column.dataIndex === 'freight'">
                        <a-input-number v-if="editTable2" v-model:value="tableData4[index].freight" :min="0" @change="tableData4[index].locked = true" />
                        <template v-else>
                          {{ formatThousandth(text) }}
                        </template>
                      </template>
                      <template
                        v-if="
                                                  ['distributionQuantity', 'remainDistributionQuantity'].includes(
                                                      column.dataIndex
                                                  )
                                              "
                        >{{ formatThousandth(text) }}</template
                      >
                      <template v-if="column.dataIndex === 'transportType'">
                        {{ transportTypeMap[text] }}
                      </template>
                    </template>
                  </a-table>
                </div>
              </div>
            </div>
            <div class="footer">
              <a-button class="btn-color" v-if="current === 3 && !saveSuccess" @click="handlerOptimize">重新优化 </a-button>
              <a-button class="btn-color" v-if="current > 0 && !saveSuccess" @click="changeCurrent(false)">上一步</a-button>
              <a-button class="btn-color" v-if="(current === 1 || current === 0) && !saveSuccess" @click="handlerValidate">下一步</a-button>
              <a-button class="btn-color" v-if="current === 2 && !saveSuccess" @click="handlerOptimize">开始优化</a-button>
              <a-button class="btn-color" v-if="current === 3 && !saveSuccess" @click="handlerSubmit">保存</a-button>
              <a-button v-if="current === 3 && saveSuccess" @click="handlerClose">关闭</a-button>
              <a-button @click="handlerUnset" v-if="!saveSuccess" class="border-btn">取消</a-button>
            </div>
          </div>
          <a-modal v-model:visible="saveVisible" title="方案另存为" @ok="handlerSave" centered width="320px">
            <a-form :model="saveFormData" ref="saveFormRef">
              <a-row>
                <a-col :span="20" offset="2">
                  <a-form-item label="配送方案名称" name="name" :rules="[{ validator: nameValidate, trigger: 'blur' }]">
                    <a-input v-model:value="saveFormData.name" />
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-modal>
          <a-modal v-model:visible="cancelVisible" @ok="handlerCancel" width="320px" centered>
            <div style="height: 80px; text-align: center; line-height: 80px; font-size: 16px"> 是否退出本页面？ </div>
          </a-modal>
        </a-spin>
        <!-- end vid_rkqe6n181v 自定义模板_wj7t65m9yw -->
      </a-spin>
    </div>
  </template>
  <script setup>
    import {
        h, ref, reactive, toRaw, markRaw, watch, computed,
        onBeforeMount, onMounted, onBeforeUnmount, onUnmounted, onActivated, onDeactivated
      } from "vue";
      import { useRoute, useRouter } from 'vue-router';
      const router = useRouter();
      const route = useRoute();
      import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
      import { cloneDeep, isNullOrEmpty, isEmptyArr, isNullOrUnDef, localGet, isContained, isArray, isEmpty,
        merge, getDifferenceArray, isObject, traversalTreeStructure, checkCaseCondition, renderStringInTemplate, handleBreadcrumbJump, throttle, permission } from '@/utils/index';
      import dayjs from 'dayjs';
      import { getPagePcChartsDataSourceConvert } from '@/utils/chart';
      import { message, notification, Modal } from 'ant-design-vue'
      import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate } from '@/utils/format';
      /*** PUBLISH_EXEGESIS ***
      import UserTableRecords from '@/model/UserTableRecords';
      *** PUBLISH_EXEGESIS ***/
  
  
  
        // 获取传入的流程ID
        const props = defineProps({
          processInstanceId: {
              type: String
          }
        })
        const immediateWatch = (source, callback) => {
          watch(source, callback, {deep: true,immediate: true })
        }
  
  
  
    /* -------------------------- 属性定义 -------------------------- */
  
        const setTimeOutList = [];
        const pageLoading = reactive({
          loading: false,
          tip: undefined
        });
  
  
  
  
        // 处理校验
        const setSubFormName =(parentInfo, name)=>{
          return [parentInfo.parents, parentInfo.cycleIndex, name];
        }
  
  
    /* ========================== 属性定义 ========================== */
  
  
    /* -------------------------- 元素数据引用 -------------------------- */
  
  
    /* ========================== 元素数据引用 ========================== */
  
  
    /* -------------------------- 页面数据 -------------------------- */
  
    /* ========================== 页面数据 ========================== */
  
  
    /* -------------------------- 响应 -------------------------- */
  
    /* ========================== 响应 ========================== */
  
  
    /* -------------------------- 函数 -------------------------- */
  
    /* ========================== 函数 ========================== */
  
  
    /* -------------------------- 页面参数 -------------------------- */
  
      const pageParameter_state = reactive({
          'processInstanceId': props.processInstanceId,
      })
  
    /* ========================== 页面参数 ========================== */
  
  
    /* -------------------------- 组件事件处理方法 -------------------------- */
  
      // ---------------------------- 组件数据同步 ----------------------------
  
      // ============================ 组件数据同步 ============================
  
  
    /* ========================== 组件事件处理方法 ========================== */
  
  
    /* -------------------------- 生命周期 -------------------------- */
    onMounted(() => {
  
      });
  
      onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
          repeat ?  clearInterval(timer): clearTimeout(timer);
        });
      });
  
    /* ========================== 生命周期 ========================== */
  
  
    /* -------------------------- 数据关联处理 -------------------------- */
  
  
  
  
  
    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */
  
    /* ========================== 数据关联处理 ========================== */
  
  
    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */
  
    /* ========================== 不同组件自定义的处理逻辑 ========================== */
  
  
    // ================================定制化逻辑========================================
    function debounce(callback, timer) {
        let ticker = null
        return () => {
            if (ticker) {
                clearTimeout(ticker)
            }
            ticker = setTimeout(() => {
                callback.apply(callback, arguments)
            }, timer)
        }
    }
  
    function downloadExcel(response, name) {
        const blob = new Blob([response], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
        })
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = name // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href)
        return href
    }
    function changeCurrent(isPlus = true) {
        if (isPlus) {
            current.value++
        } else {
            current.value--
        }
    }
  
    function handlerValidate() {
        if (current.value === 0) {
            if (tableData1.value.length == 0) {
                message.info('请先导入文件')
            } else {
                hanlderResetTable1()
                changeCurrent()
            }
        } else if (current.value === 1) {
            secondFormRef.value.validate().then(() => {
                changeCurrent()
            })
        } else if (current.value === 2) {
            changeCurrent()
        }
    }
    /**********************************  页面1 start  ****************************************/
    const current = ref(0)
    const loading = ref(false)
    const timeType = ref(1)
    const distributionRemain = ref(true)
  
    let tableData1 = ref([])
    // 并不是真克隆 保留本体但是过滤的数据发生改变 此数据也应该改变
    let tableData1Clone = []
    const filter1 = reactive({
        name: '',
        packageType: undefined
    })
    function handlerFilterTable1() {
        if (filter1.packageType === undefined) {
            filter1.packageType = ''
        }
        tableData1.value = tableData1Clone.filter(item => {
            return item.areaName.indexOf(filter1.name) !== -1 && item.packingTypeName.indexOf(filter1.packageType) !== -1
        })
        currentPage.value = 1
    }
    function hanlderResetTable1() {
        filter1.name = ''
        filter1.packageType = ''
        handlerFilterTable1()
    }
    const columns1 = [
        {
            title: '区域名称',
  
            resizable: true,
            dataIndex: 'areaName'
        },
        {
            title: '包装形式',
            resizable: true,
  
            dataIndex: 'packingTypeName'
        },
        {
            title: '产品品牌',
            resizable: true,
  
            dataIndex: 'brandName'
        },
        {
            title: '产品品种',
            resizable: true,
  
            dataIndex: 'categoryName'
        },
        {
            title: '运输方式',
            resizable: true,
  
            dataIndex: 'transportTypeName'
        },
        {
            title: '需求量(吨)',
            resizable: true,
  
            dataIndex: 'demand'
        }
    ]
    const transportTypeMap = {
        TRAIN: '火运',
        SHIP: '船运',
        BUS: '汽运'
    }
  
    const currentPage = ref(1)
    function pageChange({ current }) {
        console.log(current, 'current')
        currentPage.value = current
    }
    // 需求量变化 修改统计的相关数据
    const debounceGetStatistics = debounce(getStatistics, 300)
    const statistics = reactive({
        num1: 0,
        num2: 0,
        num3: 0,
        num4: 0
    })
    function getStatistics() {
        let num1 = 0
        let num2 = 0
        let num3 = 0
        let num4 = 0
        tableData1Clone.forEach(({ demand, packingTypeName }) => {
            num1 += Number(demand)
            packingTypeName = packingTypeName.replace('水泥', '')
            if (packingTypeName === '袋装') {
                num2 += Number(demand)
            } else if (packingTypeName === '散装') {
                num3 += Number(demand)
            } else if (packingTypeName === '熟料') {
                num4 += Number(demand)
            }
        })
        statistics.num1 = num1.toFixed(2)
        statistics.num2 = num2.toFixed(2)
        statistics.num3 = num3.toFixed(2)
        statistics.num4 = num4.toFixed(2)
    }
    function handlerDownloadTemplate() {
        get(`/solution-zjcnfsn-distribution/api/v1/template/download/distribution_optimizing_area_demand`, null, {
            responseType: 'arraybuffer'
        }).then(res => {
            if (res.data) {
                downloadExcel(res.data, '区域需求量列表模板.xlsx')
            } else {
                downloadExcel(res, '区域需求量列表模板.xlsx')
            }
        })
    }
    function beforeUpload(file) {
        const data = new FormData()
        data.append('file', file)
        loading.value = true
        post('/solution-zjcnfsn-distribution/api/v1/distribution/area_demand/import', data).then(({ errorMsg, data }) => {
            loading.value = false
            if (errorMsg) {
                message.error(errorMsg)
            } else {
                tableData1Clone = tableData1.value = data
                getStatistics()
            }
        })
        return false
    }
    /**********************************  页面1 end  ****************************************/
    /**********************************  页面2 start  ****************************************/
  
    const formatThousandth = value => {
        if (!value || isNaN(value)) {
            return value || '0.00'
        }
        const [int, fraction] = Number(value).toFixed(2).split('.')
        var reg = /(\d)(?=(?:\d{3})+$)/g
        return int.replace(reg, '$1,') + (!!fraction ? '.' + fraction : '')
    }
    function getUpperVsesion() {
        const searchForm = {
            pageNo: 1,
            pageSize: 100000
        }
        // 获取企业发货上限下拉框数据
        post('/solution-zjcnfsn-distribution/api/v1/enterprise_delivery_constraint/search/version', searchForm).then(
            ({ errorMsg, data }) => {
                if (errorMsg) {
                    message.error(errorMsg)
                } else {
                    upperLimitList.value = data.content.map(item => {
                        return {
                            label: item.versionName,
                            value: item.id
                        }
                    })
                }
            }
        )
    }
    function getUpperPackageList() {
        const param = {
            filter: {
                baseTypeId: 1
            },
            pageNo: 1,
            pageSize: 100000
        }
        post('/solution-zjcnfsn-distribution/api/v1/base_info/search', param).then(({ errorMsg, data }) => {
            if (errorMsg) {
                message.error(errorMsg)
            } else {
                packageTypeList.value = data.content.map(item => {
                    return {
                        label: item.name,
                        value: item.name
                    }
                })
            }
        })
    }
    const secondFormData = reactive({
        upperLimit: undefined
    })
    const upperLimitList = ref([])
  
    const columns2 = [
        {
            title: '企业名称',
            resizable: true,
  
            dataIndex: 'enterpriseName'
        },
        {
            title: '包装类型',
            resizable: true,
  
            dataIndex: 'packageTypeName'
        },
        {
            title: '产品品牌',
  
            resizable: true,
            dataIndex: 'brandName'
        },
        {
            title: '产品品种',
  
            resizable: true,
            dataIndex: 'categoryName'
        },
        {
            title: '运输方式',
  
            resizable: true,
            dataIndex: 'transportTypeName'
        },
        {
            title: '发运量上限',
  
            resizable: true,
            dataIndex: 'maxMonthlyDelivery'
        },
        {
            title: '操作时间',
  
            resizable: true,
            dataIndex: 'lastModifyDate'
        }
    ]
    const dataSource2 = ref([])
  
    const filter2 = reactive({
        enterpriseName: '',
        areaName: '',
        packageType: undefined
    })
    // 选中的企业发货上限的label和value在计算时需要带给后端，这里存一下
    const upperCheck = ref([])
    // 包装类型数据
    const packageTypeList = ref([])
    const secondFormRef = ref(null)
    // 上限改变时触发列表接口
    function handlerUpperChange(value, option) {
        upperCheck.value = option
        getUpperTableList()
    }
  
    // 筛选获取表格数据
    function getUpperTableList() {
        const searchForm = {
            filter: {
                enterpriseName: filter2.enterpriseName ? filter2.enterpriseName : '',
                packageTypeName: filter2.packageType ? filter2.packageType : '',
                versionId: upperCheck.value.value ? upperCheck.value.value : ''
            },
            pageNo: 1,
            pageSize: 10000
        }
        post('/solution-zjcnfsn-distribution/api/v1/enterprise_delivery_constraint/search', searchForm).then(
            ({ errorMsg, data }) => {
                if (errorMsg) {
                    message.error(errorMsg)
                } else {
                    dataSource2.value = data.content
                }
            }
        )
    }
    function handlerSearchUpper() {
        getUpperTableList()
    }
    function handlerResetUpper() {
        filter2.enterpriseName = ''
        filter2.packageType = ''
        getUpperTableList()
    }
    /**********************************  页面2 end  ****************************************/
  
    /**********************************  页面3 start  ****************************************/
    // 是否包含客戶約束
    // const customerConstraints = ref(false)
    const customerConstraintList = ref([])
    // 区域发货约束下拉框
    const regionConstraintList = ref([])
    // 运费版本
    const freightVersionList = ref([])
  
    const thirdFormData = reactive({
        regionConstrainVersion: undefined,
        factoryPriceVersion: undefined,
        freightVersion: undefined
    })
  
    const filter3 = reactive({
        enterpriseName: '',
        areaName: '',
        packingTypeName: undefined
    })
    const packingTypeNameList = ref([])
  
    const columns3 = [
        {
            title: '企业名称',
            resizable: true,
  
            dataIndex: 'enterpriseName'
        },
        {
            title: '区域名称',
            resizable: true,
  
            dataIndex: 'areaName'
        },
        {
            title: '包装类型',
            resizable: true,
  
            dataIndex: 'packageTypeName'
        },
        {
            title: '产品品牌',
  
            resizable: true,
            dataIndex: 'brandName'
        },
        {
            title: '产品品种',
  
            resizable: true,
            dataIndex: 'categoryName'
        },
        {
            title: '运输方式',
  
            resizable: true,
            dataIndex: 'transportTypeName'
        },
        {
            title: '固定发货量（吨）',
  
            resizable: true,
            dataIndex: 'minMonthlyDelivery'
        },
        {
            title: '操作时间',
  
            resizable: true,
            dataIndex: 'lastModifyDate'
        }
    ]
    const dataSource3 = ref([])
    // 企业至区域发货约束
    const constraintCheck = ref([])
    // 客户约束
    const factoryPriceCheck = ref([])
    // 运费版本
    const freightCheck = ref([])
  
    function handlerFactoryPriceSelect(value, option) {
        factoryPriceCheck.value = option
    }
    function handlerFreightSelect(value, option) {
        freightCheck.value = option
    }
    function handlerConstraintChange(value, option) {
        constraintCheck.value = option
        getConstraintTableList()
    }
    function getConstraintListVersion() {
        const searchForm = {
            pageNo: 1,
            pageSize: 100000
        }
        post('/solution-zjcnfsn-distribution/api/v1/enterprise_to_area/search/version', searchForm).then(
            ({ data, errorMsg }) => {
                if (errorMsg) {
                    message.error(errorMsg)
                } else {
                    regionConstraintList.value = data.content.map(item => {
                        return {
                            label: item.versionName,
                            value: item.id
                        }
                    })
                }
            }
        )
    }
    // 出厂价
    function getcustomFactoryPriceVersion() {
        const params = {
            pageNo: 1,
            pageSize: 100000
        }
        post('/solution-zjcnfsn-distribution/api/v1/enterprise_area_factory_price/search/version', params).then(
            ({ data, errorMsg }) => {
                console.log(data, '1')
  
                if (errorMsg) {
                    message.error(errorMsg)
                } else {
                    customerConstraintList.value = data.content.map(item => {
                        return {
                            label: item.versionName,
                            value: item.id
                        }
                    })
                }
            }
        )
    }
    function getfreightVersion() {
        const params = {
            pageNo: 1,
            pageSize: 100000
        }
        post('/solution-zjcnfsn-distribution/api/v1/enterprise_area_freight/search/version', params).then(
            ({ data, errorMsg }) => {
                console.log(data, '2')
                if (errorMsg) {
                    message.error(errorMsg)
                } else {
                    freightVersionList.value = data.content.map(item => {
                        return {
                            label: item.versionName,
                            value: item.id
                        }
                    })
                }
            }
        )
    }
    function getConstraintTableList() {
        const searchForm = {
            filter: {
                enterpriseName: filter3.enterpriseName ? filter3.enterpriseName : '',
                packageTypeName: filter3.packingTypeName ? filter3.packingTypeName : '',
                areaName: filter3.areaName ? filter3.areaName : '',
                versionId: constraintCheck.value.value ? constraintCheck.value.value : ''
            },
            pageNo: 1,
            pageSize: 10000
        }
        post('/solution-zjcnfsn-distribution/api/v1/enterprise_to_area/list', searchForm).then(({ data, errorMsg }) => {
            if (errorMsg) {
                message.error(errorMsg)
            } else {
                dataSource3.value = data.content
            }
        })
    }
    function handlerConstraintSearch() {
        getConstraintTableList()
    }
    function handlerConstraintReset() {
        filter3.enterpriseName = ''
        filter3.areaName = ''
        filter3.packingTypeName = ''
        getConstraintTableList()
    }
    /**********************************  页面3 end  ****************************************/
    /**********************************  页面4 start  ****************************************/
    const saveSuccess = ref(false)
    let tableData4 = ref([])
    let tableData4Clone = tableData4.value
    const statistics2 = reactive({
        num1: 0,
        num2: 0,
        num3: 0,
        num4: 0,
        num5: 0,
        num6: 0,
        num7: 0
    })
    function getStatistics2() {
        let num1 = 0
        let num2 = 0
        let num3 = 0
        let num4 = 0
        let num5 = 0
        let num6 = 0
        let num7 = 0
        tableData4Clone.forEach(
            ({ freight, distributionQuantity, transportType, packingTypeName, remainDistributionQuantity }) => {
                num1 += Number(freight)
  
                if (transportType === 'BUS') {
                    num2 += Number(freight)
                } else if (transportType === 'TRAIN') {
                    num3 += Number(freight)
                } else if (transportType === 'SHIP') {
                    num4 += Number(freight)
                }
                packingTypeName = packingTypeName.replace('水泥', '')
                if (packingTypeName === '袋装') {
                    num6 += Number(distributionQuantity)
                    num6 += Number(remainDistributionQuantity)
                } else if (packingTypeName === '散装') {
                    num5 += Number(distributionQuantity)
                    num5 += Number(remainDistributionQuantity)
                } else if (packingTypeName === '熟料') {
                    num7 += Number(distributionQuantity)
                    num7 += Number(remainDistributionQuantity)
                }
            }
        )
        statistics2.num1 = num1.toFixed(2)
        statistics2.num2 = num2.toFixed(2)
        statistics2.num3 = num3.toFixed(2)
        statistics2.num4 = num4.toFixed(2)
        statistics2.num5 = num5.toFixed(2)
        statistics2.num6 = num6.toFixed(2)
        statistics2.num7 = num7.toFixed(2)
    }
    const columns4 = [
        {
            title: '企业名称',
  
            resizable: true,
            dataIndex: 'enterpriseName'
        },
        {
            title: '中转仓',
  
            resizable: true,
            dataIndex: 'transferName'
        },
        {
            title: '区域名称',
  
            resizable: true,
            dataIndex: 'areaName'
        },
        {
            title: '运输方式',
  
            resizable: true,
            dataIndex: 'transportType'
        },
        {
            title: '包装类型',
  
            resizable: true,
            dataIndex: 'packingTypeName'
        },
        {
            title: '产品品牌',
  
            resizable: true,
            dataIndex: 'brandName'
        },
        {
            title: '产品品种',
  
            resizable: true,
            dataIndex: 'category'
        },
        {
            title: '配送量(吨)',
  
            resizable: true,
            dataIndex: 'distributionQuantity'
        },
        {
            title: '剩余配送量(吨)',
  
            resizable: true,
            dataIndex: 'remainDistributionQuantity'
        },
        {
            title: '配送运费(元)',
  
            resizable: true,
            dataIndex: 'freight'
        }
    ]
    let uuid = ''
    function genUUID() {
        return (Math.random() * 100000).toFixed(0)
    }
    const thirdFormRef = ref(null)
    function handlerOptimize() {
        thirdFormRef.value.validate().then(() => {
            loading.value = true
            tableData4.value = tableData4Clone = []
            const data = {
                uuid: uuid || genUUID(),
                areaDemandList: tableData1.value,
                adjustedItem: current.value === 1 ? [] : tableData4.value,
                // 剩余发货量配送最低区域
                distributionRemain: distributionRemain.value,
                // 企业发货上限约束版本id
                enterpriseDeliveryConstraintVersionId: upperCheck.value.value,
                enterpriseDeliveryConstraintVersionName: upperCheck.value.label,
                // 企业至区域需求约束版本id
                enterpriseAreaConstraintVersionId: constraintCheck.value.value,
                enterpriseAreaConstraintVersionName: constraintCheck.value.label,
                //
                enterpriseAreaFactoryPriceVersionId: factoryPriceCheck.value.value,
                enterpriseAreaFactoryPriceVersionName: factoryPriceCheck.value.label,
                enterpriseAreaFreightVersionId: freightCheck.value.value,
                enterpriseAreaFreightVersionName: freightCheck.value.label
            }
  
            let timer = null
            post('/solution-zjcnfsn-distribution/api/v1/distribution/optimize', data).then(({ errorMsg, data }) => {
                if (errorMsg) {
                    message.error(errorMsg)
                    loading.value = false
                } else {
                    distributionId.value = data
                    timer = setInterval(() => {
                        get(`/solution-zjcnfsn-distribution/api/v1/distribution/optimize/${distributionId.value}`).then(
                            ({ errorMsg, data }) => {
                                if (errorMsg) {
                                    message.error(errorMsg)
                                    loading.value = false
                                }
                                if (data) {
                                    loading.value = false
                                    tableData4.value = tableData4Clone = data
                                    clearInterval(timer)
                                    if (current.value === 2) {
                                        changeCurrent()
                                    }
                                }
                            }
                        )
                    }, 1000)
                }
            })
        })
    }
    watch(
        () => tableData4.value,
        () => {
            getStatistics2()
        }
    )
    function handlerSubmit() {
        saveVisible.value = true
    }
    function handlerClose() {
        cancelVisible.value = true
    }
    function handlerUnset() {
        cancelVisible.value = true
    }
    function handlerCancel() {
        router.push('/app_50000089/page/50000968')
    }
    const saveFormRef = ref(null)
    const nameValidate = async (rule, value, callback) => {
        if (!value) {
            return Promise.reject('请输入配送方案名称')
        }
        const { data } = await post(`/solution-zjcnfsn-distribution/api/v1/distribution/exist/${value}`)
        return data ? Promise.resolve() : Promise.reject(new Error('该配送名称重复'))
        return Promise.resolve()
    }
    const filter4 = reactive({
        enterpriseName: '',
        areaName: '',
        packingTypeName: undefined
    })
    const cancelVisible = ref(false)
    function handlerFilterTable4() {
        if (filter4.packingTypeName === undefined) {
            filter4.packingTypeName = ''
        }
  
        tableData4.value = tableData4Clone.filter(item => {
            return (
                item.enterpriseName.indexOf(filter4.enterpriseName) !== -1 &&
                item.areaName.indexOf(filter4.areaName) !== -1 &&
                item.packingTypeName.indexOf(filter4.packingTypeName) !== -1
            )
        })
    }
    function hanlderResetTable4() {
        filter4.enterpriseName = ''
        filter4.areaName = ''
        filter4.packingTypeName = ''
        handlerFilterTable4()
    }
    const saveFormData = reactive({
        name: ''
    })
    const saveVisible = ref(false)
    const distributionId = ref('')
    function handlerSave() {
        saveFormRef.value.validate().then(() => {
            loading.value = true
            post('/solution-zjcnfsn-distribution/api/v1/distribution', {
                id: Number(distributionId.value),
                name: saveFormData.name
            }).then(({ errorMsg }) => {
                loading.value = false
                if (errorMsg) {
                    message.error(errorMsg)
                } else {
                    message.success('保存成功')
                    saveVisible.value = false
                    saveSuccess.value = true
                }
            })
        })
    }
  </script>
  <style lang="less" scoped>
    .page_root {
    width: 100%;
    height: 100%;
    overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container)
     {
        height: 100%;
    }
    .table-moreBtn_down {
      overflow: hidden; white-space: nowrap; text-overflow: ellipsis; width: 100px;
    }
  
    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
      background: #ebf1ff;
    }
  
    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
      z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
      left: 15px !important;
      width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
      left: 30px !important;
      width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
      left: 45px !important;
      width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
      left: 60px !important;
      width: calc(100% - 60px);
    }
  
    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list)
     {
        height: 100%;
        width: 50%;
    }
    .vid_rkqe6n181v{
        width:100%
    }
  
    .create-plan > * {
        background: #fff;
    }
    .step {
        margin: 0 auto 10px;
        padding: 18px 12%;
    }
    .footer {
        width: 100%;
        padding: 10px 0;
        position: fixed;
        bottom: 0;
        left: 0;
        background: #fff;
        display: flex;
        justify-content: center;
    }
    .footer > * {
        margin-left: 8px;
    }
  
    .content {
        min-height: 73vh;
        padding: 24px 24px 50px;
        position: relative;
    }
    .top-div {
        height: 56px;
        background: #fafafa;
        border: 1px solid rgba(224, 32, 32, 1);
        border-radius: 2px;
        display: flex;
        justify-content: space-between;
        padding: 0 20px;
        line-height: 56px;
        color: #262626;
    }
    .top-num {
        max-width: 200px;
        overflow: hidden;
        color: #d9001b;
        font-weight: 600;
        display: block;
        margin-right: 5px;
        font-size: 20px;
        text-overflow: ellipsis;
    }
    .second-table,
    .third-table {
        margin-top: 20px;
    }
  
    .date-group .aps-form-item-control-input-content {
        display: flex;
        align-items: center;
    }
    .date-group .aps-form-item-control-input-content span {
        margin: 0 10px;
    }
    .radio {
        margin-left: 15px;
    }
    .aps-form-item-has-error .aps-radio-button-wrapper {
        border-color: #d9d9d9 !important;
    }
    .aps-form-item-has-error .aps-radio-button-wrapper:not(:first-child)::before {
        display: none;
    }
  
    .table-header {
        margin: 20px 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        text-indent: 10px;
    }
    .table-header.tag {
        border-left: 8px solid #1890ff;
    }
    .table-header div:last-child {
        display: flex;
    }
  
    .table-header div:last-child > .aps-btn {
        margin-left: 8px;
    }
  
    .gather {
        display: inline-block;
        padding: 10px 25px;
        background: linear-gradient(0deg, rgba(255, 255, 255, 1) 0%, rgba(243, 248, 254, 1) 100%);
    }
    .gather:nth-child(4) {
        margin-right: 50px;
    }
  
    .aps-upload.aps-upload-select {
        display: block;
    }
  
    .tag-list {
        align-items: center;
    }
  
    .distribution-remain {
        white-space: nowrap;
    }
    .four-top {
        margin-bottom: 20px;
    }
    .four-right {
        width: 15%;
        line-height: 80px;
    }
    .success {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    .statis-suffix {
        font-size: 14px;
        color: #333333;
        margin-left: 3px;
    }
  
    /deep/.import-div .ant3-table-cell {
        padding: 3px 16px;
    }
  
    :deep(.@{ant-prefix}-table-thead) > tr > th {
        background-color: #f5f5f5;
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 600;
        color: #262626;
        padding: 0 24px;
        height: 40px;
    }
    /deep/.ant3-steps-item-process > .ant3-steps-item-container > .ant3-steps-item-icon {
        background: #e02020;
        border: none;
    }
    .top-title {
        position: relative;
        font-size: 16px;
        font-weight: 800;
        margin-top: 21px;
        margin-left: 10px;
        margin-bottom: 21px;
        color: #262626;
    }
  
    .top-title:before {
        position: absolute;
        content: '';
        background-color: #e02020;
        width: 4px;
        height: 16px;
        position: absolute;
        left: -10px;
        top: 58%;
        margin-top: -10px;
    }
    .first-top-row,
    .second-top-row,
    .third-top-row {
        height: 32px;
        line-height: 32px;
    }
    .third-top-row {
        margin-bottom: 16px;
    }
    .first-top-row-check {
        font-size: 14px;
        color: #262626;
        font-weight: normal;
    }
    .btn-color {
        background-color: #e02020;
        color: #fff;
        border: none;
    }
    .border-btn {
        border: 1px solid #e02020;
        color: #e02020;
    }
    /deep/.ant3-form-item-label > label {
        color: #595959;
    }
    .second-top {
        border-bottom: 1px solid #d9d9d9;
        height: 48px;
        line-height: 48px;
    }
    .normal-col {
        font-weight: normal;
    }
    .four-title {
        display: flex;
        height: 80px;
        background: #fafafa;
        border: 1px solid rgba(224, 32, 32, 1);
        border-radius: 2px;
        padding: 15px 0;
    }
    .four-title-item-first {
        flex: 1;
        height: 100%;
        display: flex;
        flex-direction: column;
        border-right: 1px solid;
        border-image: linear-gradient(to bottom, #f5f5f5, #e02020, #f5f5f5) 1 100%;
        padding: 0 10px;
    }
    .four-title-item {
        display: flex;
        flex-direction: column;
        width: 14%;
        height: 100%;
        border-right: 1px solid;
        border-image: linear-gradient(to bottom, #f5f5f5, #e02020, #f5f5f5) 1 100%;
        padding: 0 16px;
    }
    .item-title {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.85);
    }
    .first-item-title {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.85);
    }
    .item-bottom {
        font-size: 20px;
        color: #e02020;
        font-weight: 600;
        line-height: 30px;
        display: flex;
    }
    .first-item-bottom {
        font-size: 20px;
        color: #e02020;
        font-weight: 600;
        line-height: 30px;
        display: flex;
    }
    .bottom-num {
        max-width: 210px;
        overflow: hidden; /*超出部分隐藏*/
        text-overflow: ellipsis;
        display: inline-block; /*超出部分省略号表示*/
    }
    /deep/.ant3-steps-item-finish .ant3-steps-item-icon {
        border-color: #e02020;
    }
    /deep/.ant3-steps-item-finish .ant3-steps-item-icon > .ant3-steps-icon {
        color: #e02020;
    }
    /deep/.ant3-steps-item-finish > .ant3-steps-item-container > .ant3-steps-item-content > .ant3-steps-item-title::after {
        background-color: #d9d9d9;
    }
    /deep/.ant3-form-item-label > label {
        font-weight: normal;
        color: #595959;
    }
    /deep/.ant3-select-single.ant3-select-show-arrow .ant3-select-selection-item,
    .ant3-select-single.ant3-select-show-arrow .ant3-select-selection-placeholder {
        color: #262626;
        font-weight: 600;
    }
    :deep(.table-striped-even) td {
        background-color: #ffffff;
        padding-left: 24px !important;
    }
    :deep(.table-striped-odd) td {
        background-color: #fafafa;
        padding-left: 24px !important;
    }
  </style>
  